package services

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/boticord/backend/notifications/app"
	"github.com/boticord/backend/notifications/types"
	"go.uber.org/fx"
	"io"
	"net/http"
)

type RpcService struct {
	auth    *AuthService
	appPort string
}

func (r *RpcService) PublishStats(token, f string, data types.Stats) (map[string]interface{}, error) {
	var buf bytes.Buffer
	encoder := json.NewEncoder(&buf)
	if err := encoder.Encode(data); err != nil {
		return map[string]interface{}{}, err
	}

	reqst, _ := http.NewRequest("POST", fmt.Sprintf("http://resources-service:%s/bots/%s/stats", r.appPort, f), &buf)
	reqst.Header.Set("Authorization", token)

	reqst.Header.Set("Content-Type", "application/json")
	client := http.Client{}
	resp, err := client.Do(reqst)
	if err != nil {
		return map[string]interface{}{}, err
	}

	d, err := io.ReadAll(resp.Body)
	if err != nil {
		return map[string]interface{}{}, err
	}
	returnData := map[string]interface{}{}
	err = json.Unmarshal(d, &returnData)
	return returnData, err
}

func newStatsService() fx.Option {
	return fx.Provide(func(auth *AuthService, config *app.Config) *RpcService {
		return &RpcService{
			auth:    auth,
			appPort: config.AppPort,
		}
	})
}
